'-----------------------------------------------------------------
'             PT DC Hub @ Direct Connect P2P Network
'-----------------------------------------------------------------
'       Developer: Carlos Ferreira (fLaSh) - Portugal
'          E-mail: carlosferreiracarlos@hotmail.com
' Project started: 10 - September - 2006
'         License: GNU General Public License.
'-----------------------------------------------------------------
'       Thanks to developers and contributores of SDCH/DDCH
'         The Left Hand, ButterflySoul, HaArD and Selyb
'  TheNOP, RollTheDice, JDommi, GhOstFaCE, ArchaicLight and TUFF
'-----------------------------------------------------------------
Option Explicit On
Option Strict Off
Imports System.Runtime.InteropServices
Imports LuaInterface
'Register a Guid class COM interface, for more info..
'search on regedit.exe for {7FFBB260-AA83-4064-B9EE-ACF11660BFC5}
<Guid("7FFBB260-AA83-4064-B9EE-ACF11660BFC5"), ComVisible(True)> _
Public Class LuaLink
    Implements IDisposable

    'All objects for Lua script interface
    Private __colUser As ShadowsClasses.clsHub
    Private __colCommands As ShadowsClasses.clsCommands
    Private __colIPBans As ShadowsClasses.clsIPBans
    Private __colRegistered As ShadowsClasses.clsRegistered
    Private __objSettings As ShadowsClasses.clsSettings
    Private __objFunctions As ShadowsClasses.clsFunctions
    Private __frmHub As ShadowsClasses.frmHub
    Private __objDebug As ShadowsClasses.cDebug
    Private __objSQLite As ShadowsClasses.clsSQLite
    Private __objChatRoom As ShadowsClasses.clsChatRoom
    Private __objRegExps As ShadowsClasses.clsRegExps
    Private __objMyIPTools As ShadowsClasses.clsMyIPTools
    Private __objZLib As ShadowsClasses.clsZLib
    Private __objBZip2 As ShadowsClasses.clsBZip2
    Private __objHuffman As ShadowsClasses.clsHuffman
    Private __objPlan As ShadowsClasses.clsPlan
    Private __objStatus As ShadowsClasses.clsStatus
    Private __objTimersAPI As ShadowsClasses.clsTimersAPI

    'Plugin propertys
    Private __DisposedValue As Boolean
    Private __Enabled As Boolean
    Private __Index As Integer
    Private __Name As String
    Private __LUA As Lua

    'Events booleans ----------------------------
    Private __StartedServing As Boolean
    Private __StoppedServing As Boolean
    Private __UserConnected As Boolean
    Private __RegConnected As Boolean
    Private __OpConnected As Boolean
    Private __UserQuit As Boolean
    Private __AddedPermBan As Boolean
    Private __AddedTempBan As Boolean
    Private __AddedRegisteredUser As Boolean
    Private __RemovedRegisteredUser As Boolean
    Private __AttemptedConnection As Boolean
    Private __DataArrival As Boolean
    Private __CustComArrival As Boolean
    Private __StartedRedirecting As Boolean
    Private __MassMessage As Boolean
    Private __FailedConf As Boolean
    Private __UnloadMain As Boolean
    Private __SubMain As Boolean
    Private __Error As Boolean
    Private __CoreError As Boolean
    Private __tmrAPI_Timer As Boolean
    'PreDataArrival--------------------------
    Private __PreDataArrival As Boolean
    Private __SupportsArrival As Boolean
    Private __ValidateNickArrival As Boolean
    Private __ChatArrival As Boolean
    Private __KeyArrival As Boolean
    Private __PasswordArrival As Boolean
    Private __VersionArrival As Boolean
    Private __GetNickListArrival As Boolean
    Private __MyINFOArrival As Boolean
    Private __SearchArrival As Boolean
    Private __ToArrival As Boolean
    Private __ConnectToMeArrival As Boolean
    Private __RevConnectToMeArrival As Boolean
    Private __SRArrival As Boolean
    Private __KickArrival As Boolean
    Private __OpForceMoveArrival As Boolean
    Private __BotINFOArrival As Boolean
    Private __UnknownArrival As Boolean
    '------------------------------------------

#Region " New/Dispose "

    Public Sub New()
        MyBase.new()
        g_LuaLink = Me
    End Sub

    'IDisposable supports
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not __DisposedValue Then
            If disposing Then
                ' TODO: free managed resources when explicitly called
                If __LUA IsNot Nothing Then
                    __LUA.Dispose()
                End If
            End If
            ' TODO: free shared unmanaged resources
            __LUA = Nothing
        End If
        __DisposedValue = True
    End Sub

    'This code added to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

#End Region

#Region " Plugin Propertys/Ini "
    <ComVisible(True)> _
    Public Function LoadPlug(ByVal oCore As Object) As Integer
        '------------------------------------------------------------------
        'Purpose:   This just allows the IDE to know
        '           if the plug-ins was loaded
        '
        'Params:    none
        '
        'Returns:   1 = plug-ins was loaded
        '------------------------------------------------------------------
        Core = oCore
        Return 1
    End Function

    <ComVisible(True)> _
    Public Property Index() As Integer
        Get
            Return __Index
        End Get
        Set(ByVal value As Integer)
            __Index = value
        End Set
    End Property

    <ComVisible(True)> _
    Public Property Name() As String
        Get
            Return __Name
        End Get
        Set(ByVal Value As String)
            __Name = Value
        End Set
    End Property

    <ComVisible(True)> _
    Public ReadOnly Property Enabled() As Boolean
        Get
            Return __Enabled
        End Get
    End Property

    <ComVisible(True)> _
    Public ReadOnly Property Version() As Double
        Get
            Return 5.1
        End Get
    End Property

    <ComVisible(True)> _
    Public ReadOnly Property Lua() As Object
        Get
            Return __LUA
        End Get
    End Property
#End Region

#Region " Public/Private Subs/Functions "
    <ComVisible(True)> _
    Public Function UseEvent(ByVal sName As String) As Boolean
        '------------------------------------------------------------------
        'Purpose:   Called by core to check if script function exist
        '
        'Params:    event name
        '
        'Returns:   true/false
        '------------------------------------------------------------------
        Try
            If __LUA Is Nothing Then Return False

            Select Case sName.ToLower
                Case "startedserving" : Return __StartedServing
                Case "stoppedserving" : Return __StoppedServing
                Case "userconnected" : Return __UserConnected
                Case "regconnected" : Return __RegConnected
                Case "opconnected" : Return __OpConnected
                Case "userquit" : Return __UserQuit
                Case "addedpermban" : Return __AddedPermBan
                Case "addedtempban" : Return __AddedTempBan
                Case "addedregistereduser" : Return __AddedRegisteredUser
                Case "removedregistereduser" : Return __RemovedRegisteredUser
                Case "attemptedconnection" : Return __AttemptedConnection
                Case "dataarrival" : Return __DataArrival
                Case "custcomarrival" : Return __CustComArrival
                Case "startedredirecting" : Return __StartedRedirecting
                Case "massmessage" : Return __MassMessage
                Case "failedconf" : Return __FailedConf
                Case "unloadmain" : Return __UnloadMain
                Case "submain" : Return __SubMain
                Case "error" : Return __Error
                Case "coreerror" : Return __CoreError
                Case "tmrapi_timer" : Return __tmrAPI_Timer
                Case "predataarrival"
                    Return __PreDataArrival Or _
                           __SupportsArrival Or _
                           __ValidateNickArrival Or _
                           __ChatArrival Or _
                           __KeyArrival Or _
                           __PasswordArrival Or _
                           __VersionArrival Or _
                           __GetNickListArrival Or _
                           __MyINFOArrival Or _
                           __SearchArrival Or _
                           __ToArrival Or _
                           __ConnectToMeArrival Or _
                           __RevConnectToMeArrival Or _
                           __SRArrival Or _
                           __KickArrival Or _
                           __OpForceMoveArrival Or _
                           __BotINFOArrival Or _
                           __UnknownArrival
            End Select
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Name & " - UseEvent()")
        End Try
    End Function

    <ComVisible(True)> _
    Public Function CheckSyntax(ByVal sCode As String, _
                       Optional ByVal bOnErrAddLog As Boolean = True, _
                       Optional ByVal bRunEvents As Boolean = True) As String
        '------------------------------------------------------------------
        'Purpose:   Called by core to check syntax error
        '
        'Params:    sCode: the source code
        '           bOnErrAddLog: add code to script log
        'Returns:   string emppty (no error) or error description
        '------------------------------------------------------------------
        Dim strError As String = ""

        Try

            Dim oLUA As Lua = NewLua()

            If InStr(sCode, vbNullChar) Then
                sCode = Replace(sCode, vbNullChar, "")
            End If

            oLUA.DoString(sCode)

            'Run Main
            If bRunEvents Then
                strError = RunTest("Main")
                strError = RunTest("UnloadMain")
            End If

            oLUA.Dispose()
            oLUA = Nothing

        Catch ex As LuaException
            strError = ex.Message
        Catch ex As Exception
            strError = ex.Message
        End Try

        Try
            If bOnErrAddLog And strError <> "" Then
                OnError("Syntax Error: " & strError, "")
            End If
        Catch ex As Exception
            OnError(ex.Message, "CheckSyntax(" & sCode & ", " & bOnErrAddLog.ToString & ", " & bRunEvents.ToString & ")")
        End Try

        Return strError

    End Function

    <ComVisible(True)> _
    Public Function AddCode(ByVal sCode As String, ByVal bRunMain As Boolean) As String
        '------------------------------------------------------------------
        'Purpose:   Called by core to start script engine
        '
        'Params:    sCode: the source code
        '           bRunMain: true: run Main() envent
        'Returns:   string emppty (no error) or 
        '            error description (and stop engine)
        '------------------------------------------------------------------
        Dim strError As String = ""

        Try

            If InStr(sCode, vbNullChar) Then
                sCode = Replace(sCode, vbNullChar, "")
            End If

            __LUA = NewLua()

            If __LUA IsNot Nothing Then
                __LUA.DoString(sCode)
                strError = SFindEvents()
                If bRunMain Then
                    If strError = "" Then
                        strError = RunTest("Main")
                    End If
                End If
            Else
                __Enabled = False
                Return "AddCode Error - NewLua()"
            End If

        Catch ex As LuaException
            strError = ex.Message
        Catch ex As Exception
            strError = ex.Message
        End Try

        Try

            If strError = "" Then
                __Enabled = True
            Else
                If __LUA IsNot Nothing Then
                    __LUA.Dispose()
                    __LUA = Nothing
                End If
                __Enabled = False
            End If

        Catch ex As Exception
            OnError(ex.Message, "AddCode(" & sCode & ")")
            If __LUA IsNot Nothing Then
                __LUA.Dispose()
                __LUA = Nothing
            End If
            __Enabled = False
        End Try
        Return strError
    End Function

    <ComVisible(True)> _
    Public Sub Reset()
        '------------------------------------------------------------------
        'Purpose:   Called by core to stop script engine
        '
        'Params:    none
        'Returns:   none
        '------------------------------------------------------------------
        Try
            If __LUA IsNot Nothing Then
                __LUA.Dispose()
                __LUA = Nothing
            End If
        Catch ex As Exception
            OnError(ex.Message, "Reset()")
        End Try
    End Sub

    Private Sub OnError(ByVal sDesciption As String, ByVal sFunction As String)
        '------------------------------------------------------------------
        'Purpose:   Called by this class, when any script error happens
        '
        'Params:    sDesciption: the error description
        '           sFunction: the function name
        'Returns:   none
        '------------------------------------------------------------------
        Try
            Me.Error(sDesciption & "[" & sFunction & "]")
            Core.Lua_Error(__Index, __Name, "Syntax Error: (" & sFunction & ") Desciption: " & sDesciption)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Name & " - OnError()")
        End Try
    End Sub

    Private Function NewLua() As Lua
        '------------------------------------------------------------------
        'Purpose:   Called by this class, to get new Lua object (used for
        '               CheckSyntax and AddCode)
        '
        'Params:    none
        'Returns:   new Lua object (with all objects and functions registered)
        '------------------------------------------------------------------
        Try
            Dim oLua As New Lua

            __colUser = New ShadowsClasses.clsHub
            __colCommands = New ShadowsClasses.clsCommands
            __colIPBans = New ShadowsClasses.clsIPBans
            __colRegistered = New ShadowsClasses.clsRegistered
            __objSettings = New ShadowsClasses.clsSettings
            __objFunctions = New ShadowsClasses.clsFunctions
            __frmHub = New ShadowsClasses.frmHub(Core)
            __objDebug = New ShadowsClasses.cDebug
            __objSQLite = New ShadowsClasses.clsSQLite
            __objChatRoom = New ShadowsClasses.clsChatRoom
            __objRegExps = New ShadowsClasses.clsRegExps
            __objMyIPTools = New ShadowsClasses.clsMyIPTools
            __objZLib = New ShadowsClasses.clsZLib
            __objBZip2 = New ShadowsClasses.clsBZip2
            __objHuffman = New ShadowsClasses.clsHuffman
            __objPlan = New ShadowsClasses.clsPlan
            __objStatus = New ShadowsClasses.clsStatus
            __objTimersAPI = New ShadowsClasses.clsTimersAPI

            oLua("colUsers") = __colUser
            oLua("colCommands") = __colCommands
            oLua("colIPBans") = __colIPBans
            oLua("colRegistered") = __colRegistered
            oLua("Settings") = __objSettings
            'oLua("Functions") = __objFunctions
            oLua("Core") = __frmHub
            oLua("Debug") = __objDebug
            oLua("SQLite") = __objSQLite
            oLua("ChatRoom") = __objChatRoom
            oLua("RegExps") = __objRegExps
            oLua("MyIPTools") = __objMyIPTools
            oLua("ZLib") = __objZLib
            oLua("BZip2") = __objBZip2
            oLua("Huffman") = __objHuffman
            oLua("Scheduler") = __objPlan
            oLua("Status") = __objStatus
            oLua("TimersAPI") = __objTimersAPI

            RegisterFunction("print", oLua, Me)

            RegisterFunction("MsgBox", oLua, __objFunctions)
            RegisterFunction("LoadObj", oLua, __objFunctions)
            RegisterFunction("UnloadObj", oLua, __objFunctions)
            RegisterFunction("NewCollection", oLua, __objFunctions)
            RegisterFunction("NewHuffman", oLua, __objFunctions)
            RegisterFunction("NewBZip2", oLua, __objFunctions)
            RegisterFunction("NewZLib", oLua, __objFunctions)
            RegisterFunction("NewXMLParser", oLua, __objFunctions)
            RegisterFunction("NewXMLNode", oLua, __objFunctions)
            RegisterFunction("NewXMLAttribute", oLua, __objFunctions)
            RegisterFunction("NewJetEngine", oLua, __objFunctions)
            RegisterFunction("NewConnection", oLua, __objFunctions)
            RegisterFunction("NewSQLite", oLua, __objFunctions)
            RegisterFunction("NewDictionary", oLua, __objFunctions)
            RegisterFunction("AfterFirst", oLua, __objFunctions)
            RegisterFunction("BeforeFirst", oLua, __objFunctions)
            RegisterFunction("AfterLast", oLua, __objFunctions)
            RegisterFunction("BeforeLast", oLua, __objFunctions)
            RegisterFunction("BetweenFirst", oLua, __objFunctions)
            RegisterFunction("BetweenLast", oLua, __objFunctions)
            RegisterFunction("LastPosition", oLua, __objFunctions)
            RegisterFunction("ShellExec", oLua, __objFunctions)
            RegisterFunction("ShareSize", oLua, __objFunctions)
            RegisterFunction("DBDate", oLua, __objFunctions)
            RegisterFunction("ClassName", oLua, __objFunctions)
            RegisterFunction("ClassNameList", oLua, __objFunctions)
            RegisterFunction("TickCount", oLua, __objFunctions)
            RegisterFunction("Alert", oLua, __objFunctions)
            RegisterFunction("Prompt", oLua, __objFunctions)
            RegisterFunction("ShowBallon", oLua, __objFunctions)
            RegisterFunction("RandomChars", oLua, __objFunctions)
            RegisterFunction("CUser", oLua, __objFunctions)
            RegisterFunction("CObj", oLua, __objFunctions)
            RegisterFunction("GetENLangStr", oLua, __objFunctions)
            RegisterFunction("ValidLang", oLua, __objFunctions)
            RegisterFunction("AddScriptMessages", oLua, __objFunctions)
            RegisterFunction("AddScriptMessage", oLua, __objFunctions)
            RegisterFunction("GetSegment", oLua, __objFunctions)
            RegisterFunction("SplitParameter", oLua, __objFunctions)
            RegisterFunction("DictItemDel", oLua, __objFunctions)
            RegisterFunction("ForceMinLen", oLua, __objFunctions)
            RegisterFunction("ReplaceHubVars", oLua, __objFunctions)
            RegisterFunction("ReplaceUserVars", oLua, __objFunctions)
            RegisterFunction("NMDCUnescape", oLua, __objFunctions)
            RegisterFunction("NMDCEscape", oLua, __objFunctions)

            Return oLua

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Name & " - NewLua()")
            Return Nothing
        End Try
    End Function

    Private Function SFindEvents() As String
        '------------------------------------------------------------------
        'Purpose:   Called by this class when starting script engine to
        '           set bools of the events used by this script
        '
        'Params:    none
        'Returns:   string emppty (no error) or error description
        '------------------------------------------------------------------
        Dim sReturn As String = ""
        Try
            __StartedServing = False
            __StoppedServing = False
            __UserConnected = False
            __RegConnected = False
            __OpConnected = False
            __UserQuit = False
            __AddedPermBan = False
            __AddedTempBan = False
            __AddedRegisteredUser = False
            __RemovedRegisteredUser = False
            __AttemptedConnection = False
            __DataArrival = False
            __CustComArrival = False
            __StartedRedirecting = False
            __MassMessage = False
            __FailedConf = False
            __UnloadMain = False
            __SubMain = False
            __Error = False
            __CoreError = False
            __tmrAPI_Timer = False
            'PreDataArrival--------------------------
            __PreDataArrival = False
            __SupportsArrival = False
            __ValidateNickArrival = False
            __ChatArrival = False
            __KeyArrival = False
            __PasswordArrival = False
            __VersionArrival = False
            __GetNickListArrival = False
            __MyINFOArrival = False
            __SearchArrival = False
            __ToArrival = False
            __ConnectToMeArrival = False
            __RevConnectToMeArrival = False
            __SRArrival = False
            __KickArrival = False
            __OpForceMoveArrival = False
            __BotINFOArrival = False
            __UnknownArrival = False
            '------------------------------------------
            __StartedServing = SFindEnvent("StartedServing", sReturn)
            __StoppedServing = SFindEnvent("StoppedServing", sReturn)
            __UserConnected = SFindEnvent("UserConnected", sReturn)
            __RegConnected = SFindEnvent("RegConnected", sReturn)
            __OpConnected = SFindEnvent("OpConnected", sReturn)
            __UserQuit = SFindEnvent("UserQuit", sReturn)
            __AddedPermBan = SFindEnvent("AddedPermBan", sReturn)
            __AddedTempBan = SFindEnvent("AddedTempBan", sReturn)
            __AddedRegisteredUser = SFindEnvent("AddedRegisteredUser", sReturn)
            __RemovedRegisteredUser = SFindEnvent("RemovedRegisteredUser", sReturn)
            __AttemptedConnection = SFindEnvent("AttemptedConnection", sReturn)
            __DataArrival = SFindEnvent("DataArrival", sReturn)
            __CustComArrival = SFindEnvent("CustComArrival", sReturn)
            __StartedRedirecting = SFindEnvent("StartedRedirecting", sReturn)
            __MassMessage = SFindEnvent("MassMessage", sReturn)
            __FailedConf = SFindEnvent("FailedConf", sReturn)
            __UnloadMain = SFindEnvent("UnloadMain", sReturn)
            __SubMain = SFindEnvent("SubMain", sReturn)
            __Error = SFindEnvent("Error", sReturn)
            __CoreError = SFindEnvent("CoreError", sReturn)
            __tmrAPI_Timer = SFindEnvent("tmrAPI_Timer", sReturn)
            'PreDataArrival---------------------------------------------------------------------
            __PreDataArrival = SFindEnvent("PreDataArrival", sReturn)
            __SupportsArrival = SFindEnvent("SupportsArrival", sReturn)
            __ValidateNickArrival = SFindEnvent("ValidateNickArrival", sReturn)
            __ChatArrival = SFindEnvent("ChatArrival", sReturn)
            __KeyArrival = SFindEnvent("KeyArrival", sReturn)
            __PasswordArrival = SFindEnvent("PasswordArrival", sReturn)
            __VersionArrival = SFindEnvent("VersionArrival", sReturn)
            __GetNickListArrival = SFindEnvent("GetNickListArrival", sReturn)
            __MyINFOArrival = SFindEnvent("MyINFOArrival", sReturn)
            __SearchArrival = SFindEnvent("SearchArrival", sReturn)
            __ToArrival = SFindEnvent("ToArrival", sReturn)
            __ConnectToMeArrival = SFindEnvent("ConnectToMeArrival", sReturn)
            __RevConnectToMeArrival = SFindEnvent("RevConnectToMeArrival", sReturn)
            __SRArrival = SFindEnvent("SRArrival", sReturn)
            __KickArrival = SFindEnvent("KickArrival", sReturn)
            __OpForceMoveArrival = SFindEnvent("OpForceMoveArrival", sReturn)
            __BotINFOArrival = SFindEnvent("BotINFOArrival", sReturn)
            __UnknownArrival = SFindEnvent("UnknownArrival", sReturn)
            '-----------------------------------------------------------------------------------

        Catch ex As Exception
            sReturn &= "SFindEvents - " & ex.Message
        End Try

        Return sReturn

    End Function

    Private Function SFindEnvent(ByVal sName As String, ByRef sError As String) As Boolean
        '------------------------------------------------------------------
        'Purpose:   Called by this class (SFindEvents) to check in Lua code
        '           If the function name (sName) exist
        '
        'Params:    sName: fuction name; sError: data returned (ByRef)
        '               string emppty (no error) or error description
        'Returns:   true/false
        '------------------------------------------------------------------
        Try
            Dim oLuaFunction As LuaFunction = TryCast(__LUA.GetFunction(sName), LuaFunction)
            Return CBool(oLuaFunction IsNot Nothing)
        Catch ex As LuaException
            sError = "SFindEnvent - " & ex.Message
        Catch ex As Exception
            sError = "SFindEnvent - " & ex.Message
        End Try
    End Function

    Private Sub RegisterFunction(ByVal sName As String, ByVal oLua As Lua, ByVal oClass As Object)
        '------------------------------------------------------------------
        'Purpose:   Called by this class to register a lua function on lua
        '           object
        '
        'Params:    sName: fuction name; sError: data returned (ByRef)
        '               string emppty (no error) or error description
        '           oLua: the lua object 
        'Returns:   none
        '------------------------------------------------------------------
        Try
            Dim oMinfo As System.Reflection.MethodInfo
            oMinfo = oClass.GetType.GetMethod(sName)
            oLua.RegisterFunction(sName, oClass, oMinfo)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, __Name & " - RegisterFunction(" & sName & ")")
        End Try
    End Sub

    Private Function RunTest(ByVal sEvent As String) As String
        '------------------------------------------------------------------
        'Purpose:   Called by this class to run function (Main() and UnloadMain())
        '
        'Params:    sEvent: fuction name; sError: data returned 
        '           oLua: the lua object 
        'Returns:   string emppty (no error) or 
        '           error description 
        '------------------------------------------------------------------
        Try
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction(sEvent), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call]()
            End If
        Catch ex As LuaException
            Return ex.Message
        Catch ex As Exception
            Return ex.Message
        End Try
        Return ""
    End Function

    Public Function print(ByVal sText As String) As Object
        '------------------------------------------------------------------
        'Purpose:   Called by script function print("....")
        '
        'Params:    sText: the string data
        'Returns:   0
        '------------------------------------------------------------------
        Core.AddScriptLog(__Name, sText)
        Return 0
    End Function
#End Region

#Region " PTDCH API Hub Events "

    '------------------------------------------------------------------
    'Purpose:   Scripts events interface
    '           Called when the hub owner presses the envents
    '
    'Returns:   Depends of the envents
    '           Events with returns:
    '                   -PreDataArrival
    '                         = Empty: the data won't be processed
    '                        <> Empty: the data will be processed
    '                   -FailedConf
    '                         = True:  the data won't be processed
    '                         = False: the data will be processed
    '------------------------------------------------------------------

    '--------------------------------------------------------------
    'Triggered when hub start serving
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub StartedServing()
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("StartedServing"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call]()
            End If
        Catch ex As LuaException
            OnError(ex.Message, "StartedServing()")
        Catch ex As Exception
            OnError(ex.Message, "StartedServing()")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when hub stop serving
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub StoppedServing()
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("StoppedServing"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call]()
            End If
        Catch ex As LuaException
            OnError(ex.Message, "StoppedServing()")
        Catch ex As Exception
            OnError(ex.Message, "StoppedServing()")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a non registered user has logged in.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub UserConnected(ByRef oUser As Object)
        Try
            If __LUA Is Nothing Then Exit Sub
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("UserConnected"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](xUser)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "UserConnected(" & oUser.sName & ")")
        Catch ex As Exception
            OnError(ex.Message, "UserConnected(" & oUser.sName & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a registered user has logged in.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub RegConnected(ByRef oUser As Object)
        Try
            If __LUA Is Nothing Then Exit Sub
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("RegConnected"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](xUser)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "RegConnected(" & oUser.sName & ")")
        Catch ex As Exception
            OnError(ex.Message, "RegConnected(" & oUser.sName & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when an Operator has logged in.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub OpConnected(ByRef oUser As Object)
        Try
            If __LUA Is Nothing Then Exit Sub
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("OpConnected"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](xUser)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "OpConnected(" & oUser.sName & ")")
        Catch ex As Exception
            OnError(ex.Message, "OpConnected(" & oUser.sName & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a user has logged out.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub UserQuit(ByRef oUser As Object)
        Try
            If __LUA Is Nothing Then Exit Sub
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("UserQuit"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](xUser)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "UserQuit(" & oUser.sName & ")")
        Catch ex As Exception
            OnError(ex.Message, "UserQuit(" & oUser.sName & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a new permanent ban is added to the hub's database.( colIPBans.Add )
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub AddedPermBan(ByRef sIP As String, ByRef sNick As String, ByRef sBannedBy As String, ByRef sReason As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("AddedPermBan"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sIP, sNick, sBannedBy, sReason)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "AddedPermBan(" & sIP & ", " & sNick & ", " & sBannedBy & ", " & sReason & ")")
        Catch ex As Exception
            OnError(ex.Message, "AddedPermBan(" & sIP & ", " & sNick & ", " & sBannedBy & ", " & sReason & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a new temporary ban is added to the hub's database.( colIPBans.Add )
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub AddedTempBan(ByRef sIP As String, ByRef lMinutes As Integer, ByRef sNick As String, ByRef sBannedBy As String, ByRef sReason As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("AddedTempBan"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sIP, lMinutes, sNick, sBannedBy, sReason)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "AddedTempBan(" & sIP & ", " & lMinutes & ", " & sNick & ", " & sBannedBy & ", " & sReason & ")")
        Catch ex As Exception
            OnError(ex.Message, "AddedTempBan(" & sIP & ", " & lMinutes & ", " & sNick & ", " & sBannedBy & ", " & sReason & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a new user is added to the hub's database. ( colRegistered.Add )
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub AddedRegisteredUser(ByVal sName As String, ByVal sPassword As String, ByVal iClass As Integer, ByVal sAdminName As String, ByVal lMin As Integer)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("AddedRegisteredUser"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sName, sPassword, iClass, sAdminName, lMin)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "AddedRegisteredUser(" & sName & ", " & sPassword & ", " & iClass & ", " & sAdminName & ", " & lMin & ")")
        Catch ex As Exception
            OnError(ex.Message, "AddedRegisteredUser(" & sName & ", " & sPassword & ", " & iClass & ", " & sAdminName & ", " & lMin & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when a new user is removed from the hub's database. ( colRegistered.Rem )
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub RemovedRegisteredUser(ByVal sName As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("RemovedRegisteredUser"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sName)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "RemovedRegisteredUser(" & sName & ")")
        Catch ex As Exception
            OnError(ex.Message, "RemovedRegisteredUser(" & sName & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when there is a new connection to the listening port(s).
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub AttemptedConnection(ByVal sIP As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("AttemptedConnection"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sIP)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "AttemptedConnection(" & sIP & ")")
        Catch ex As Exception
            OnError(ex.Message, "AttemptedConnection(" & sIP & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered whenever a connected user send data.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub DataArrival(ByRef oUser As Object, ByVal sData As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("DataArrival"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](xUser, sData)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "DataArrival(" & oUser.sName & ", " & sData & ")")
        Catch ex As Exception
            OnError(ex.Message, "DataArrival(" & oUser.sName & ", " & sData & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when the hub command prefix is detected in a user's message to the hub.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub CustComArrival(ByRef oUser As Object, ByRef oCommand As Object, ByRef sMessage As String, ByRef bMainChat As Boolean)
        Try
            If __LUA Is Nothing Then Exit Sub
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            Dim xCommand As New ShadowsClasses.clsCommand(oCommand)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("CustComArrival"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](xUser, xCommand, sMessage, bMainChat)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "CustComArrival(" & oUser.sName & ", " & sMessage & ", " & bMainChat.ToString & ")")
        Catch ex As Exception
            OnError(ex.Message, "CustComArrival(" & oUser.sName & ", " & sMessage & ", " & bMainChat.ToString & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when the hub command prefix is detected in a user's message to the hub.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub StartedRedirecting()
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("StartedRedirecting"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call]()
            End If
        Catch ex As LuaException
            OnError(ex.Message, "StartedRedirecting()")
        Catch ex As Exception
            OnError(ex.Message, "StartedRedirecting()")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when m_sending a Mass message. (Tru interface)
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub MassMessage(ByRef sMessage As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("MassMessage"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sMessage)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "MassMessage(" & sMessage & ")")
        Catch ex As Exception
            OnError(ex.Message, "MassMessage(" & sMessage & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when this plugin is stop. Do your cleanup here.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Function FailedConf(ByRef oUser As Object, ByRef iType As Integer) As Boolean
        '------------------------------------------------------------------
        'Purpose:   Allow to bypass the hub's rules settings
        '           Triggered whenever a user fail a hub's rules.
        '
        'Params:    oUser: The user m_sending the data.
        '           intType: Integer telling what rule the user failled
        '
        'Comments:  See: Enum enuAlert in the help file.
        '
        '           False = Let the hub take care of the user,
        '           message the user,  banning and/or disconnecting him.
        '------------------------------------------------------------------
        Try
            Dim blnRequest() As Object
            If __LUA Is Nothing Then Exit Function
            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("FailedConf"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                blnRequest = oLuaFunction.[Call](xUser, iType)
                If Not IsNothing(blnRequest) Then
                    If Not IsNothing(blnRequest(0)) Then
                        If TypeOf blnRequest(0) Is Boolean Or TypeOf blnRequest(0) Is Integer Then
                            Return CBool(blnRequest(0))
                        End If
                    End If
                End If
            End If
        Catch ex As LuaException
            OnError(ex.Message, "FailedConf(" & oUser.sName & ", " & iType.ToString & ")")
        Catch ex As Exception
            OnError(ex.Message, "FailedConf(" & oUser.sName & ", " & iType.ToString & ")")
        End Try
    End Function

    '--------------------------------------------------------------
    'Triggered when this plugin is stop. Do your cleanup here.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub UnloadMain()
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("UnloadMain"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call]()
            End If
        Catch ex As LuaException
            OnError(ex.Message, "UnloadMain()")
        Catch ex As Exception
            OnError(ex.Message, "UnloadMain()")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when this plugin is start
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub SubMain()
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("Main"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call]()
            End If
        Catch ex As LuaException
            OnError(ex.Message, "Main()")
        Catch ex As Exception
            OnError(ex.Message, "Main()")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when this plugin is start
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub [Error](ByVal sDescription As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("Error"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sDescription)
            End If
        Catch : End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when this plugin is start
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub CoreError(ByVal sDescription As String)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("CoreError"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](sDescription)
            End If
        Catch : End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered when some API timer is called
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Sub tmrAPI_Timer(ByVal Index As Integer)
        Try
            If __LUA Is Nothing Then Exit Sub
            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction("tmrAPI_Timer"), LuaFunction)
            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                oLuaFunction.[Call](Index)
            End If
        Catch ex As LuaException
            OnError(ex.Message, "tmrAPI_Timer(" & Index.ToString & ")")
        Catch ex As Exception
            OnError(ex.Message, "tmrAPI_Timer(" & Index.ToString & ")")
        End Try
    End Sub

    '--------------------------------------------------------------
    'Triggered whenever a connected user send data.
    '--------------------------------------------------------------
    <ComVisible(True)> _
    Public Function PreDataArrival(ByVal oUser As Object, ByVal sCommand As String) As String
        '------------------------------------------------------------------
        'Purpose:   Allow data string to be modified before the hub see it
        '           Triggered whenever the hub receive data from an accepted connection
        '
        'Params:    oUser: The user m_sending the data.
        '                    sCommand: The data received. (Might have already been modify by an other plugin.)
        '
        'Comments:  PreDataArrival = Empty : Prevent any further processing by the Hub and other plugin/script.
        '           PreDataArrival = [same or modified string] : The data will be further processed by the hub and plugins/scripts

        '------------------------------------------------------------------
        Dim strRequest As Object
        Dim strCommand As String = sCommand
        Dim strExtention As String

        Try
            If __LUA Is Nothing Then Return String.Empty

            'Bulid a class temp to declare all propertys, subs and functions..
            Dim xUser As New ShadowsClasses.clsUser(oUser)

            If __PreDataArrival Then
                'First get your function (on the script)
                Dim oLuaFunction As LuaFunction = _
                        TryCast(__LUA.GetFunction("PreDataArrival"), LuaFunction)
                If oLuaFunction IsNot Nothing Then
                    strRequest = oLuaFunction.[Call](xUser, sCommand)
                    If Not IsNothing(strRequest) Then
                        If Not IsNothing(strRequest(0)) Then
                            If TypeOf strRequest(0) Is String Then
                                strCommand = strRequest.ToString
                                If String.IsNullOrEmpty(strCommand) Then
                                    Return String.Empty
                                End If
                            End If
                        End If
                    End If
                End If
            End If

            If sCommand.Contains(" ") Then
                strExtention = Split(sCommand, " ")(0).Trim
            Else
                strExtention = sCommand.Trim
            End If

            Select Case strExtention.ToLower
                Case "$supports" '- Incoming supports from user.
                    If __SupportsArrival Then PreDataExt(xUser, strCommand, "SupportsArrival", False)
                Case "$key" '- Incoming key from user.
                    If __KeyArrival Then PreDataExt(xUser, strCommand, "KeyArrival", False)
                Case "$validatenick" '- Incoming validate nick from user.
                    If __ValidateNickArrival Then PreDataExt(xUser, strCommand, "ValidateNickArrival", False)
                Case "$mypass" '- Incoming password from user.
                    If __PasswordArrival Then PreDataExt(xUser, strCommand, "PasswordArrival", False)
                Case "$version" '- Incoming version from user.
                    If __VersionArrival Then PreDataExt(xUser, strCommand, "VersionArrival", False)
                Case "$getnicklist" '- Incoming get nick list request from user. If script return true hub don't process data.
                    If __GetNickListArrival Then
                        If PreDataExt(xUser, strCommand, "VersionArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$myinfo" '- Incoming user myinfo.
                    If __MyINFOArrival Then PreDataExt(xUser, strCommand, "MyINFOArrival", False)
                Case "$search" '- Incoming search request from user. If script return true hub don't process data.
                    If __SearchArrival Then
                        If PreDataExt(xUser, strCommand, "SearchArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$to:" '- Incoming private message from user. If script return true hub don't process data.
                    If __ToArrival Then
                        If PreDataExt(xUser, strCommand, "ToArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$connecttome" '- Incoming active connection request from user. If script return true hub don't process data.
                    If __ConnectToMeArrival Then
                        If PreDataExt(xUser, strCommand, "ConnectToMeArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$revconnecttome" '- Incoming pasive connection request from user. If script return true hub don't process data.
                    If __RevConnectToMeArrival Then
                        If PreDataExt(xUser, strCommand, "RevConnectToMeArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$sr" '- Incoming search reply from user. If script return true hub don't process data.
                    If __SRArrival Then
                        If PreDataExt(xUser, strCommand, "SRArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$kick" '- Incoming kick command from user. If script return true hub don't process data.
                    If __KickArrival Then
                        If PreDataExt(xUser, strCommand, "KickArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$opforcemove" '- Incoming redirect command from user. If script return true hub don't process data.
                    If __OpForceMoveArrival Then
                        If PreDataExt(xUser, strCommand, "OpForceMoveArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case "$botinfo" '- Incoming hublist pinger request from user. If script return true hub don't process data.
                    If __BotINFOArrival Then
                        If PreDataExt(xUser, strCommand, "BotINFOArrival") Then
                            Return String.Empty
                        End If
                    End If
                Case Else  '- Incoming chat message from user. If script return true hub don't process data.
                    If strExtention.StartsWith("<") Then
                        Dim sPos As Integer = strCommand.LastIndexOf(oUser.sName) + oUser.sName.Length + 2 'Remove the <nick>
                        Dim sMessage As String = strCommand.Substring(sPos)
                        If __ChatArrival Then
                            If PreDataExt(xUser, sMessage, "ChatArrival") Then
                                Return String.Empty
                            End If
                        End If
                    Else '- Incoming unknown command from user. If script return true hub don't process data (don't disconnect user).
                        If __UnknownArrival Then
                            If PreDataExt(xUser, strCommand, "UnknownArrival") Then
                                Return String.Empty
                            End If
                        End If
                    End If
            End Select

        Catch ex As LuaException
            OnError(ex.Message, "PreDataArrival(" & oUser.sName & ", " & sCommand & ")")
        Catch ex As Exception
            OnError(ex.Message, "PreDataArrival(" & oUser.sName & ", " & sCommand & ")")
        End Try

        Return strCommand

    End Function
 
    '--------------------------------------------------------------
    'EXTRA PTDCH Events (for max. compatible ptokax scripts ;-))
    '--------------------------------------------------------------
    Private Function PreDataExt(ByVal tUser As ShadowsClasses.clsUser, _
                                ByVal sData As String, _
                                ByVal sFunction As String, _
                       Optional ByVal bReturnBool As Boolean = True) As Boolean
        Try
            If __LUA Is Nothing Then Exit Function

            Dim blnRequest() As Object

            'First get your function (on the script)
            Dim oLuaFunction As LuaFunction = _
                    TryCast(__LUA.GetFunction(sFunction), LuaFunction)

            'Check if it exsists in the LUA script
            If oLuaFunction IsNot Nothing Then
                'Get lua return params
                blnRequest = oLuaFunction.[Call](tUser, sData)
                If bReturnBool Then
                    If Not IsNothing(blnRequest) Then
                        If Not IsNothing(blnRequest(0)) Then
                            If TypeOf blnRequest(0) Is Boolean Or TypeOf blnRequest(0) Is Integer Then
                                Return CBool(blnRequest(0))
                            Else
                                If IsNumeric(blnRequest(0)) Then
                                    Return CBool(blnRequest(0))
                                End If
                            End If
                        End If
                    End If
                End If
            End If

        Catch ex As LuaException
            OnError(ex.Message, sFunction & "(" & tUser.sName & ", " & sData & ")")
        Catch ex As Exception
            OnError(ex.Message, sFunction & "(" & tUser.sName & ", " & sData & ")")
        End Try
    End Function

#End Region

End Class
